<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :width="1000">
    <BasicForm @register="registerForm" >
      <!-- 插槽： -->
      <template #signalId>
        <a-transfer
          v-model:target-keys="targetKeys"
          :data-source="dataSource"
          :disabled="false"
          :show-search="false"
          :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
          :show-select-all="false"
          @change="handleChange"
        >
          <template #children="{direction, filteredItems, selectedKeys,
                    disabled: listDisabled, onItemSelectAll, onItemSelect}">
            <a-table :row-selection="getRowSelection(
                    {disabled: listDisabled, selectedKeys,onItemSelectAll, onItemSelect})"
                     :columns="direction === 'left' ? leftColumns : rightColumns"
                     :data-source="filteredItems" size="small" row-key="id" bordered
                     :style="{ pointerEvents: listDisabled ? 'none' : null }"
                     :custom-row="({ key, disabled: itemDisabled }) => ({
                      onClick: () => {
                        if (itemDisabled || listDisabled) return;
                        onItemSelect(key, !selectedKeys.includes(key));
                      },
                    })"/>
          </template>
        </a-transfer>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../pointGroup.data';
  import { list, saveOrUpdatePointGroup, getPointGroupById } from '../pointGroup.api';
  import { getSignalByModel } from '../../signal/signal.api';
  import { getDeviceModelByType } from '../../deviceModel/deviceModel.api';
  import { isArray } from '/@/utils/is';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  // 穿梭框自定义列表内容
  const leftColumns = ref([
    {dataIndex: 'name', title: '点位名称', align: 'center', width: 180},
    // {dataIndex: 'address', title: '点位地址', align: 'center', width: 180},
    {dataIndex: 'fieldName', title: '字段名称', align: 'center', width: 180},
  ]);
  const rightColumns = ref([
    {dataIndex: 'name', title: '点位名称', align: 'center', width: 180},
    // {dataIndex: 'address', title: '点位地址', align: 'center', width: 180},
    {dataIndex: 'fieldName', title: '字段名称', align: 'center', width: 180}
  ]);
  const dataSource = ref<[]>([]);
  const targetKeys = ref<string[]>([]);

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    targetKeys.value = [];
    
    //获取下拉树信息
    const result = await list({});
    const treeData = result.data ? result.data : [];
    treeData.unshift({id:'0', name:'请选择父类型'});

    updateSchema([
      {
        field: 'pid',
        componentProps: { treeData },
      },
    ]);

    if (unref(isUpdate)) {
      //获取详情
      data.record = await getPointGroupById({ id: data.record.id });
      targetKeys.value = data.record.signalIds;
    }
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      let values = { ...data.record };
      setFieldsValue(values);
    }

    updateSchema({ field: 'modelId', componentProps:  ({ formModel }) =>{
      return {
        api: getDeviceModelByType,
        params: {typeId: formModel.typeId},
        labelField: 'model',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: async (v,item) => {
          let modelId = '';
          if(isArray(v)){
            modelId = v[0];
          }else{
            modelId = v;
          }
          dataSource.value=[];
          const dataList = await getSignalByModel({modelId: modelId});
          if(dataList){
            dataList.forEach(element => {
            dataSource.value.push({
                id: element.id,
                key: element.id,
                name: element.name,
                fieldName: element.fieldName,
                disabled: false,
              });
            });
          }
        }
      };
    }});
  });

  //设置标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增点位组' : '编辑点位组'));

  //表单提交事件
  async function handleSubmit() {
    try {
      const values = await validate();
      values.signalIds = targetKeys.value;
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdatePointGroup(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  //穿梭框事件
  function getRowSelection({disabled, selectedKeys, onItemSelectAll, onItemSelect}) {
      return {
        getCheckboxProps: item => ({
          disabled: disabled || item.disabled,
        }),

        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter(item => {
            if("disabled" in item){ 
              return !item.disabled;
            }
            return true;
          }).map(({key}) => key);
          onItemSelectAll(treeSelectedKeys, selected);
        },

        onSelect({ key}, selected) {
          onItemSelect(key, selected);
        },

        selectedRowKeys: selectedKeys,
      };
  }

  function handleChange(nextTargetKeys: string[]){
    console.log('nextTargetKeys', targetKeys.value, nextTargetKeys);
  }
</script>
